<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>三关一闭监控系统</title>
    
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css" />
    <!-- Element Plus Icons CSS -->
    <link rel="stylesheet" href="https://unpkg.com/@element-plus/icons-vue/dist/index.css" />
    
    <!-- 自定义样式 -->
    <link rel="stylesheet" href="public/styles.css" />
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        /* 顶部导航 */
        .header {
            background: #fff;
            border-bottom: 1px solid #e0e0e0;
            padding: 0 30px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .logo {
            font-size: 20px;
            font-weight: 600;
            color: #333;
        }
        
        .header-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .refresh-info {
            font-size: 14px;
            color: #666;
        }
        
        .refresh-btn {
            padding: 8px 16px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .refresh-btn:hover {
            background: #40a9ff;
        }
        
        .last-update {
            font-size: 14px;
            color: #999;
        }
        
        /* 主容器 */
        .main-container {
            padding: 20px 30px;
            max-width: 100%;
        }
        
        /* 统计卡片区域 */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 16px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 4px;
            border: 1px solid #e8e8e8;
        }
        
        .stat-label {
            font-size: 14px;
            color: #999;
            margin-bottom: 8px;
        }
        
        .stat-value {
            font-size: 28px;
            font-weight: 600;
            color: #333;
        }
        
        /* 门店区域 */
        .shop-section {
            background: white;
            border-radius: 4px;
            border: 1px solid #e8e8e8;
            margin-bottom: 20px;
        }
        
        .shop-header {
            padding: 16px 20px;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .shop-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        
        .shop-info {
            font-size: 14px;
            color: #666;
        }
        
        /* 表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table thead {
            background: #fafafa;
        }
        
        .data-table th {
            padding: 12px 16px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
            color: #666;
            border-bottom: 1px solid #e8e8e8;
        }
        
        .data-table td {
            padding: 16px;
            font-size: 14px;
            color: #333;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .data-table tbody tr:hover {
            background: #fafafa;
        }
        
        /* 状态标签 */
        .status-badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-online {
            background: #f6ffed;
            color: #52c41a;
            border: 1px solid #b7eb8f;
        }
        
        .status-offline {
            background: #fff1f0;
            color: #ff4d4f;
            border: 1px solid #ffccc7;
        }
        
        .status-closed {
            background: #e6f7ff;
            color: #1890ff;
            border: 1px solid #91d5ff;
        }
        
        .status-open {
            background: #fff7e6;
            color: #fa8c16;
            border: 1px solid #ffd591;
        }
        
        /* 操作按钮 */
        .action-btn {
            padding: 6px 12px;
            background: white;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            color: #333;
            transition: all 0.3s;
        }
        
        .action-btn:hover {
            color: #1890ff;
            border-color: #1890ff;
        }
        
        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
            font-size: 14px;
        }
        
        /* 空状态 */
        .empty {
            text-align: center;
            padding: 40px;
            color: #999;
            font-size: 14px;
        }
        
        /* 确认模态框 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.45);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background: white;
            border-radius: 4px;
            width: 420px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .modal-header {
            padding: 16px 24px;
            border-bottom: 1px solid #e8e8e8;
            font-size: 16px;
            font-weight: 600;
        }
        
        .modal-body {
            padding: 24px;
        }
        
        .modal-info-row {
            display: flex;
            margin-bottom: 12px;
            font-size: 14px;
        }
        
        .modal-label {
            width: 100px;
            color: #666;
        }
        
        .modal-value {
            flex: 1;
            color: #333;
            font-weight: 500;
        }
        
        .modal-warning {
            margin-top: 16px;
            padding: 12px;
            background: #fffbe6;
            border: 1px solid #ffe58f;
            border-radius: 4px;
            font-size: 13px;
            color: #ad6800;
        }
        
        .modal-footer {
            padding: 10px 16px;
            border-top: 1px solid #e8e8e8;
            text-align: right;
        }
        
        .modal-btn {
            padding: 7px 15px;
            border-radius: 4px;
            border: 1px solid #d9d9d9;
            background: white;
            cursor: pointer;
            font-size: 14px;
            margin-left: 8px;
        }
        
        .modal-btn-primary {
            background: #1890ff;
            border-color: #1890ff;
            color: white;
        }
        
        .modal-btn-primary:hover {
            background: #40a9ff;
            border-color: #40a9ff;
        }
        
        .modal-btn:hover {
            color: #1890ff;
            border-color: #1890ff;
        }
        
        /* 电力状态区域 */
        .power-status-section {
            padding: 12px 20px;
            background: #f9f9f9;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .power-status-info {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .power-label {
            font-size: 14px;
            color: #666;
            font-weight: 500;
        }
        
        .power-status-text {
            font-size: 14px;
            font-weight: 600;
            padding: 4px 12px;
            border-radius: 4px;
            background: #e8e8e8;
            color: #666;
        }
        
        /* 红绿灯样式 */
        .power-light {
            font-size: 24px;
            display: inline-block;
            transition: all 0.3s;
            user-select: none;
        }
        
        .power-light:hover {
            transform: scale(1.2);
        }
        
        .power-light-green {
            color: #67c23a;
            text-shadow: 0 0 8px #67c23a;
        }
        
        .power-light-red {
            color: #f56c6c;
            text-shadow: 0 0 8px #f56c6c;
        }
        
        .power-light-gray {
            color: #909399;
        }
        
        .power-light-querying {
            color: #e6a23c;
            animation: blink 1s infinite;
        }
        
        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.3; }
        }
        
        .power-status-text.power-on {
            background: #fff1f0;
            color: #ff4d4f;
        }
        
        .power-status-text.power-off {
            background: #f6ffed;
            color: #52c41a;
        }
        
        .power-status-text.querying {
            background: #e6f7ff;
            color: #1890ff;
        }
        
    </style>
</head>
<body>
    <!-- 顶部导航 -->
    <div class="header">
        <div class="logo">🔒 三关一闭监控系统</div>
        <div class="header-right">
            <div class="refresh-info">
                最后更新: <span id="lastUpdate">--:--:--</span>
            </div>
            <button class="refresh-btn" onclick="fetchData()">🔄 刷新</button>
        </div>
    </div>

    <!-- 主容器 -->
    <div class="main-container">
        <!-- 统计卡片 -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-label">门店总数</div>
                <div class="stat-value" id="totalShops">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">传感器总数</div>
                <div class="stat-value" id="totalSensors">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">在线传感器</div>
                <div class="stat-value" id="onlineSensors">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">已开启</div>
                <div class="stat-value" style="color: #fa8c16;" id="openCount">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">已关闭</div>
                <div class="stat-value" style="color: #52c41a;" id="closedCount">0</div>
            </div>
        </div>

        <!-- 门店列表 -->
        <div id="shopList"></div>
    </div>

    <!-- 确认模态框 -->
    <div id="confirmModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">设置关闭状态</div>
            <div class="modal-body">
                <div class="modal-info-row">
                    <div class="modal-label">安装位置</div>
                    <div class="modal-value" id="modalPosition">--</div>
                </div>
                <div class="modal-info-row">
                    <div class="modal-label">传感器MAC</div>
                    <div class="modal-value" id="modalMac">--</div>
                </div>
                <div class="modal-info-row">
                    <div class="modal-label">传感器型号</div>
                    <div class="modal-value" id="modalModel">--</div>
                </div>
                <div class="modal-info-row">
                    <div class="modal-label">综合角度</div>
                    <div class="modal-value" id="modalAngle">--</div>
                </div>
                <div class="modal-warning">
                    ⚠️ 此操作将把当前状态设置为<strong>关闭状态基准值</strong>，后续会以此判断设备是否关闭。
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" onclick="closeModal()">取消</button>
                <button class="modal-btn modal-btn-primary" onclick="confirmSetClosed()">确认设置</button>
            </div>
        </div>
    </div>

    <script>
        let selectedSensor = null;

        // 页面加载时获取数据
        window.onload = function() {
            fetchData();
            // 每5秒自动刷新
            setInterval(fetchData, 500);
        };

        // 获取数据
        async function fetchData() {
            try {
                const response = await fetch('http://localhost:8080/api/real-time/status');
                const data = await response.json();
                
                if (data.success) {
                    renderData(data.shops);
                    updateLastUpdateTime();
                } else {
                    showError(data.message || '获取数据失败');
                }
            } catch (error) {
                console.error('获取数据失败:', error);
                showError('网络错误，请检查后端服务是否启动');
            }
        }

        // 渲染数据
        function renderData(shops) {
            let totalShops = shops.length;
            let totalSensors = 0;
            let onlineSensors = 0;
            let openCount = 0;
            let closedCount = 0;

            // 统计数据
            shops.forEach(shop => {
                
                if (shop.sensors) {
                    totalSensors += shop.sensors.length;
                    shop.sensors.forEach(sensor => {
                        if (sensor.isOnline) onlineSensors++;
                        if (sensor.state === 'open') openCount++;
                        if (sensor.state === 'closed') closedCount++;
                    });
                }
            });

            // 更新统计卡片
            document.getElementById('totalShops').textContent = totalShops;
            document.getElementById('totalSensors').textContent = totalSensors;
            document.getElementById('onlineSensors').textContent = onlineSensors;
            document.getElementById('openCount').textContent = openCount;
            document.getElementById('closedCount').textContent = closedCount;

            // 渲染门店列表
            const shopListHtml = shops.map(shop => renderShop(shop)).join('');
            document.getElementById('shopList').innerHTML = shopListHtml || '<div class="empty">暂无数据</div>';
        }

        // 渲染单个门店
        function renderShop(shop) {
            const shopInfo = shop.shopInfo || {};
            const gateway = shop.gateway || {};
            const sensors = shop.sensors || [];

            if (sensors.length === 0) {
                return '';
            }

            const shopId = shopInfo.id || '';
            const powerStatusId = `power-status-${shopId}`;
            
            return `
                <div class="shop-section">
                    <div class="shop-header">
                        <div class="shop-title">${shopInfo.name || '未命名门店'}</div>
                        <div class="shop-info">
                            网关: ${gateway.gatewayMac || 'N/A'} | 
                            信号: ${gateway.signalStrength || 'N/A'} dBm | 
                            传感器数: ${sensors.length}
                        </div>
                    </div>
                    <div class="power-status-section">
                        <div class="power-status-info">
                            <span class="power-label">电力状态：</span>
                            <span 
                                id="${powerStatusId}" 
                                class="power-light power-light-gray" 
                                onclick="showPowerDetails('${shopId}', '${shopInfo.name || '未命名门店'}')"
                                title="点击查看详情"
                                style="cursor: pointer;"
                            >⚪</span>
                            <span class="power-label" style="margin-left: 15px;">上次查询：</span>
                            <span id="${powerStatusId}-time" class="power-status-text" style="font-size: 13px;">--</span>
                        </div>
                        <button class="action-btn" onclick="queryShopPower('${shopId}', '${shopInfo.name || '未命名门店'}')">
                            查询电力
                        </button>
                    </div>
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th style="width: 180px;">设备ID</th>
                                <th style="width: 100px;">型号</th>
                                <th style="width: 150px;">安装位置</th>
                                <th style="width: 100px;">在线状态</th>
                                <th style="width: 120px;">状态</th>
                                <th style="width: 100px;">信号强度</th>
                                <th style="width: 100px;">综合角度</th>
                                <th style="width: 100px;">综合圈数</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${sensors.map(sensor => renderSensorRow(sensor, gateway.gatewayMac, shopInfo)).join('')}
                        </tbody>
                    </table>
                </div>
            `;
        }

        // 渲染传感器行
        function renderSensorRow(sensor, gatewayMac, shopInfo) {
            const isOnline = sensor.isOnline || false;
            const state = sensor.state || 'unknown';
            const installName = sensor.installPositionName || sensor.installPosition || '未设置';
            
            // 型号显示：统一显示IM600
            const modelDisplay = 'IM600';

            // 综合角度
            const compositeAngle = (sensor.compositeAngle !== undefined && sensor.compositeAngle !== null) 
                ? sensor.compositeAngle.toFixed(2) + '°'
                : 'N/A';
            
            // 综合圈数：字段值为1就显示，为0就不显示
            let rotationCountDisplay = '-';
            
            if (sensor.useMultiTurnDetection === 1 && sensor.compositeRotationCount !== null && sensor.compositeRotationCount !== undefined) {
                rotationCountDisplay = sensor.compositeRotationCount.toFixed(2) + '圈';
            }
            
            const signalStrength = (sensor.rssi !== undefined && sensor.rssi !== null) 
                ? Math.abs(sensor.rssi) + ' dBm'
                : 'N/A';

            const onlineStatus = isOnline 
                ? '<span class="status-badge status-online">在线</span>'
                : '<span class="status-badge status-offline">离线</span>';

            // 状态显示
            let stateStatus = '<span class="status-badge">未知</span>';
            if (state === 'closed') {
                stateStatus = '<span class="status-badge status-closed">已关闭</span>';
            } else if (state === 'open') {
                stateStatus = '<span class="status-badge status-open">已开启</span>';
            }

            // 设为关闭按钮
            const setClosedButton = `<button class="action-btn" onclick="openSetClosedModal('${sensor.sensorId}', '${installName}', '${modelDisplay}', '${compositeAngle}')">设为关闭</button>`;

            return `
                <tr>
                    <td>${sensor.sensorId}</td>
                    <td>${modelDisplay}</td>
                    <td>${installName}</td>
                    <td>${onlineStatus}</td>
                    <td>${stateStatus}</td>
                    <td>${signalStrength}</td>
                    <td>${compositeAngle}</td>
                    <td>${rotationCountDisplay}</td>
                    <td>${setClosedButton}</td>
                </tr>
            `;
        }

        // 打开设置模态框
        function openSetClosedModal(sensorId, installName, sensorModel, compositeAngle) {
            selectedSensor = sensorId;
            document.getElementById('modalPosition').textContent = installName;
            document.getElementById('modalMac').textContent = sensorId;
            document.getElementById('modalModel').textContent = sensorModel;
            document.getElementById('modalAngle').textContent = compositeAngle;
            document.getElementById('confirmModal').style.display = 'flex';
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('confirmModal').style.display = 'none';
            selectedSensor = null;
        }

        // 确认设置关闭状态
        async function confirmSetClosed() {
            if (!selectedSensor) return;

            try {
                const response = await fetch(`http://localhost:8080/api/sensor/${selectedSensor}/set-closed`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                const result = await response.json();
                
                if (result.success) {
                    alert('✅ 关闭基准值设置成功！');
                    closeModal();
                    fetchData(); // 刷新数据
                } else {
                    alert('❌ 设置失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('设置失败:', error);
                alert('❌ 网络错误，请重试');
            }
        }

        // 更新最后更新时间
        function updateLastUpdateTime() {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('zh-CN');
            document.getElementById('lastUpdate').textContent = timeStr;
        }

        // 显示错误
        function showError(message) {
            document.getElementById('shopList').innerHTML = `<div class="empty">${message}</div>`;
        }
        
        // 存储电力查询详情
        const powerQueryDetails = {};
        
        // 显示电力查询详情
        function showPowerDetails(shopId, shopName) {
            const details = powerQueryDetails[shopId];
            if (!details) {
                alert('暂无查询记录\n请先点击"查询电力"按钮进行查询');
                return;
            }
            
            let message = `店铺: ${shopName}\n`;
            message += `查询时间: ${details.queryTime}\n`;
            message += `总体状态: ${details.allPowerOff ? '✓ 全部断电' : '✗ 部分有电'}\n\n`;
            message += '各路状态 (1-18路):\n';
            
            const channels = details.channels || {};
            for (let i = 1; i <= 18; i++) {
                const powerOn = channels[i];
                if (powerOn === null || powerOn === undefined) {
                    // 未查询该路
                    continue;
                }
                message += `  第${i}路: ${powerOn ? '❌ 有电' : '✅ 断电'}\n`;
            }
            
            alert(message);
        }
        
        // 查询店铺电力状态
        async function queryShopPower(shopId, shopName) {
            const statusElement = document.getElementById(`power-status-${shopId}`);
            const timeElement = document.getElementById(`power-status-${shopId}-time`);
            
            if (!statusElement) {
                alert('无法找到状态显示元素');
                return;
            }
            
            try {
                // 显示查询中状态（黄色闪烁的灯）
                statusElement.className = 'power-light power-light-querying';
                statusElement.textContent = '🟡';
                if (timeElement) {
                    timeElement.textContent = '查询中...';
                }
                
                // 调用后端API进行实时查询（会自动存入Redis）
                const response = await fetch('http://localhost:8080/api/power/default/query/all/sync', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                const result = await response.json();
                
                if (result.success && result.merchantStatus) {
                    const powerData = result.merchantStatus;
                    const allPowerOff = powerData.allPowerOff;
                    const hasData = powerData.hasData;
                    const updateTime = powerData.updateTime;
                    const queryTimeStr = updateTime ? new Date(updateTime).toLocaleString('zh-CN') : new Date().toLocaleString('zh-CN');
                    
                    // 更新查询时间
                    if (timeElement) {
                        timeElement.textContent = queryTimeStr;
                    }
                    
                    if (hasData) {
                        // 存储查询详情
                        powerQueryDetails[shopId] = {
                            allPowerOff: allPowerOff,
                            channels: powerData.channels || {},
                            queryTime: queryTimeStr
                        };
                        
                        // 更新红绿灯状态
                        if (allPowerOff) {
                            // 全部断电（触发）= 绿灯
                            statusElement.className = 'power-light power-light-green';
                            statusElement.textContent = '🟢';
                        } else {
                            // 部分有电（未触发）= 红灯
                            statusElement.className = 'power-light power-light-red';
                            statusElement.textContent = '🔴';
                        }
                        
                        // 自动显示详细信息
                        showPowerDetails(shopId, shopName);
                    } else {
                        statusElement.className = 'power-light power-light-gray';
                        statusElement.textContent = '⚪';
                        alert(`店铺"${shopName}"暂无电力数据\n请确认电力设备已正确配置`);
                    }
                } else {
                    statusElement.className = 'power-light power-light-gray';
                    statusElement.textContent = '⚪';
                    if (timeElement) {
                        timeElement.textContent = new Date().toLocaleString('zh-CN');
                    }
                    alert('查询失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('查询电力状态失败:', error);
                statusElement.className = 'power-light power-light-gray';
                statusElement.textContent = '⚪';
                if (timeElement) {
                    timeElement.textContent = new Date().toLocaleString('zh-CN');
                }
                alert('查询失败: ' + error.message);
            }
        }
    </script>
</body>
</html>
